package com.foreknow.demo8;

import java.util.*;
import java.util.concurrent.Callable;

/**
 * List<Student>集合的排序
 * 两种方式
 * 1. 让Student实现接口Comparable
 * 2. 调用 Collections.sort(list,comparator);给参数传递一个comparator
 *
 * 任务： 根据姓名排序
 */
public class Student implements Comparable<Student> {
    private String name;
    private Integer age;

    public Student() {

    }

    public Student(String name,Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    /**
     * 将此对象与指定的对象进行比较以进行排序。
     * 返回一个负整数，零或正整数，因为该对象小于，等于或大于指定对象。
     * @param o
     * @return
     */
    @Override
    public int compareTo(Student o) {
        if(this.age > o.getAge()) {
            return 1;
        }else if(this.age < o.getAge()){
            return -1;
        }else {
            return 0;
        }
    }

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        Student s1 = new Student("T",18);
        Student s2 = new Student("H",28);
        Student s3 = new Student("Z",50);
        Student s4 = new Student("M",100);
        //将以上对象添加到list集合中
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        //按照年龄排序（自然顺序，由小到大）  注意：Collection接口与Collections（对集合操作的工具类）的区别
        Collections.sort(list);
        //遍历
        Iterator<Student> it = list.iterator();
        while (it.hasNext()) {
            Student student = it.next();
            System.out.println(student.getName()+" "+student.getAge());
        }

        System.out.println("---------------倒序排序---------------------");
        Comparator<Student> comparator = Collections.reverseOrder();
        Collections.sort(list,comparator);
        Iterator<Student> it_reverse = list.iterator();
        while (it_reverse.hasNext()) {
            Student s = it_reverse.next();
            System.out.println(s.getName()+" "+s.getAge());
        }

        System.out.println("---------------根据姓名排序---------------------");
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Iterator<Student> it_comparator = list.iterator();
        while (it_comparator.hasNext()) {
            Student s = it_comparator.next();
            System.out.println(s.getName()+" "+s.getAge());
        }
    }
}
